<template>
  <div class="syllabus">
    <TopTitle>
      <template #icon>
        <div class="icon" @click="
          showDesign(showOption.id, showOption.name)
          ">
          <div v-if="isPreview&&useUserStore().rolesName=='老师组'">
            <span class="iconfont icon-browse"></span> <span>预览</span>
          </div>
        </div>
      </template>
    </TopTitle>
    <div class="content">
      <div class="main">
        <div v-for="(item, index) in outline" :key="index">
          <div class="chapter finish public bigChapter">
            <div class="title">
              <div class="num">第{{ index + 1 }}章</div>
              <div class="text" v-show="!item.edit">{{ item.name }}</div>
              <div class="ipt" v-show="item.edit">
                <el-input v-model.trim="item.name" size="large" placeholder="请输入章节名称，字数限制在2-30" ref="chapterRef"
                  @keyup.enter="editChapter(index)" :maxlength="30" :minlength="2" show-word-limit />
              </div>
            </div>
            <div v-if="useUserStore().rolesName=='老师组'" class="acts">
              <div class="edit" @click="editChapter(index)">
                {{ item.edit ? "完成" : "重命名" }}
              </div>
              <div class="del">
                <el-popconfirm title="是否确认删除?" confirm-button-text="确认删除" @confirm="delChapter(item,item.id)">
                  <template #reference> 删除</template>
                </el-popconfirm>
              </div>
            </div>
          </div>
          <div v-for="(i, iidx) in item.sections" :key="iidx">
            <div class="lesson finish public">
              <div class="title">
                <div class="num">{{ iidx + 1 }}.</div>
                <div class="text" v-show="!i.edit" @click="showDesign()">
                  {{ i.name }}
                </div>
                <div class="ipt" v-show="i.edit">
                  <el-input v-model.trim="i.name" size="large" :ref="'lessonRef' + '' + index + '' + iidx"
                    placeholder="请输入小节名称，字数限制在2-30" @keyup.enter="editLesson(index, iidx)" :maxlength="30"
                    :minlength="2" show-word-limit />
                </div>
              </div>

              <div v-if="useUserStore().rolesName=='老师组'" class="acts">
                <div class="edit" @click="editLesson(index, iidx)">
                  {{ i.edit ? "完成" : "重命名" }}
                </div>
                <div class="del">
                  <el-popconfirm title="是否确认删除?" confirm-button-text="确认删除" @confirm="delLesson(i.id)">
                    <template #reference> 删除</template>
                  </el-popconfirm>
                </div>
                <div class="go">
                  <el-button @click="goDesignDialog(i)" type="primary" round plain :disabled="i.edit">教学设计
                    <span class="iconfont icon-resonserate"></span></el-button>
                </div>
              </div>

              <div class="acts" v-else>
                <div @click="showDesign(i.id, i.name)"
                    type="primary"
                    round
                    plain
                    :disabled="i.add" class="go"> 
                    查看  
                </div>
              </div>
            </div>
          </div>
          <div v-if="useUserStore().rolesName=='老师组'" class="lesson add public" @click="addLesson(index)">
            + 新增小节
          </div>
        </div>
        <div v-if="useUserStore().rolesName=='老师组'" class="isShowAdd">
          <div class="chapter add public" @click="addChapter">
            + 添加章节
          </div>
          <div class="lesson add public" @click="addLesson" v-show="!outline.length">
            + 新增小节
          </div>
        </div> 
      </div>

      <div style="display: flex; justify-content: center; align-items: center; height: 80vh" v-if="useUserStore().rolesName=='管理组'&&outline.length==0"  >
             <el-empty :image-size="200"  description='暂无大纲内容' />
        </div>

 

      
    </div>
  </div>

  <!-- 教学设计弹出层 -->
  <syllabusDialog ref="sDialog" :clockStatusMap="clockStatusMap"></syllabusDialog>
</template>

<script setup>
import TopTitle from "@/components/TopTitle.vue";
import syllabusDialog from "./syllabus-dialog.vue";
import { getCurrentInstance, reactive, watch } from "vue";
import { ElMessage, ElPopconfirm, ElLoading } from "element-plus";
import {
  outlineList,
  addoutline,
  upoutLine,
  delOutline
} from "@/api/outline";
import {
  teachDesignDetail,
  upDesignDetail,
} from "@/api/chapter";
import { materialOne } from "@/api/material";
import "@/assets/styles/dialog.css";
import { giveEllipsisStr1, getFileHzm } from "@/utils/common";
import useUserStore from '@/store/modules/user'
import { ref } from "vue";
import { counterStore } from "@/store/modules/counter"
const store = counterStore()
const sDialog = ref(null);
const subsection = ref()
const route = useRoute();
const router = useRouter();
const loading = ref(true)
const dialogVisible = ref(false);
const { proxy } = getCurrentInstance();
const showOption = ref({});
// 定义新增章节大纲字段

const addOutLineData = ref({
  name: "",
  parent_id: 0,//要新增章节的时候，这个值一定是0
  bk_id:Number(store.bkItem.id)//来自于班课基础信息主表id
})
// const savaState = ref(false);
const isChange = ref(false); //记录当前内容是否有变化，当离开页面时提醒用户保存所做的修改
const tmpChangeContent = ref(""); //暂存修改之前的内容，用于比较内容是否有改动


//定义大纲列表
const outline = ref([]);

// let hisOutLine = []; //原始大纲信息
// const isloading = ref(false);
// const loading = ref(true);
//获取素材的基础素材
const materialOption = ref({
  //素材列表查询条件
  resLibId: window.sessionStorage.getItem("libId"),
  pageSize: 7,
  pageNum: 0,
  name: "",
  type: "0",
});

const isPreview = ref(false);
const materialData = ref([]); //素材列表
// 左侧导航区域
const clockStatusMap = ref([
  {
    label: "关联视频",
    value: "0",
  },
  {
    label: "关联课件",
    value: "1",
  },
  {
    label: "关联资料",
    value: "2",
  },
]);

//预览教学设计效果
const showDesign = (id,name) => {
  router.push({ path: `/chapter`, query: {name:name} });
  sessionStorage.setItem("nodeid", id);
  sessionStorage.setItem('outlineData', JSON.stringify(outline.value));
};



//获取素材列表-视频
// const getMaterialList = () => {
//   loading.value = true
//   materialList(materialOption.value)
//     .then((res) => {
//       // console.log(res.rows);
//       loading.value = false
//       materialTotal.value = res.total;
//       materialData.value = res.rows;
//     })
//     .catch(() => { });
// };

//获取大纲列表
const getSyllList = () => {
  outlineList(addOutLineData.value.bk_id).then(res => {
    // 控制遮罩层的显示隐藏
    loading.value = false;
    // savaState.value = false;
    // 大纲列表扁平化结构转成树形结构
    const result = [];
    res.forEach(item => {
      if (item.parent_id === 0) {
        const chapter = { ...item, sections: [] };
        result.push(chapter);
        item.chapter = chapter;
      } else {
        const parentChapter = res.find(c => c.id === item.parent_id).chapter;
        parentChapter.sections.push(item);
      }
    });

    outline.value = result
    console.log(outline.value);
     // 设置点击预览时间传递的参数预览课程的（第一节标题及id）
       showOption.value.id = outline.value[0].sections[0].id;
      showOption.value.name = outline.value[0].sections[0].name;
    // 有小节的时候显示预览
    isPreview.value = outline.value.some((item) => item.sections.length)
    
  }).catch(() => {
      loading.value = false;
  
    })
};

// 新增大纲的方法
const addOutLine=(options)=>{
  addoutline(options).then(res=>{
    console.log(res);
    getSyllList()
  })
}

// 更新大纲的方法
const upDareOutLine=(options)=>{
  upoutLine(options).then(res=>{
    console.log(res);
    getSyllList()
  })
}

//新增章节
let addChapter = async () => {
  if (!(await verifyAdd())) {
    return;
  }
  outline.value.push({ name: "", edit: true, sections: [] });
  // savaState.value = true;
  tmpChangeContent.value = "";
  proxy.$nextTick(() => {
    proxy.$refs["chapterRef"][outline.value.length - 1].focus();
  }, 50);
};

//修改章(点击完成)
let editChapter = async (index) => {
  addOutLineData.value.name = outline.value[index].name
  if (outline.value[index].edit) {
    if (!(await valueEmpty(outline.value[index].name, "章节名称"))) {
      return;
    }
    //保存时需要判断内容是否发生了改变
    if (tmpChangeContent.value != outline.value[index].name) {
      isChange.value = true;
    }
    if(!outline.value[index].id){
      let obj={
            name:addOutLineData.value.name,
            parent_id:0,
            bk_id:addOutLineData.value.bk_id

      }
      console.log("新增章节");
      console.log(obj);
      addOutLine(obj)
    }else{
      console.log("更新章节");
       let obj={
            id:outline.value[index].id,
            name:outline.value[index].name,
            parent_id:outline.value[index].parent_id,
            bk_id:outline.value[index].bk_id
         }
       upDareOutLine(obj)
    }


  } else {
   
    if (!(await verifyAdd())) {
      return;
    }
    tmpChangeContent.value = outline.value[index].name;
   
  }
  outline.value[index].edit = !outline.value[index].edit;

  // proxy.$refs["chapterRef"][index].focus();
};
//新增节
let addLesson = async (index) => {
  if (!(await verifyAdd())) {
    return;
  }
  if (!outline.value[index]) {
    ElMessage.error("请新增章后再建小节");
    return;
  }
  // savaState.value = true;
  let sections = outline.value[index].sections || [];
  sections.push({ edit: true, add: true });
  tmpChangeContent.value = "";
  //小结新增时光标定位  gyzheng 20220621

  proxy.$nextTick(() => {
    let pos = "lessonRef" + index + "" + (sections.length - 1);
    proxy.$refs[pos][0].focus();
  });
};

//修改节(点击完成)
let editLesson = async (index, iidx) => {
  addOutLineData.value.name = outline.value[index].sections[iidx].name
  addOutLineData.value.parent_id=outline.value[index].id

  if (outline.value[index].sections[iidx].edit) {
    if (
      !(await valueEmpty(outline.value[index].sections[iidx].name, "小结名称"))
    ) {
      return;
    }
    //保存时需要判断内容是否发生了改变
    if (tmpChangeContent.value != outline.value[index].sections[iidx].name) {
      isChange.value = true;
    }

    if(!outline.value[index].sections[iidx].id){ 
      console.log("新增小节");
      
      addOutLine(addOutLineData.value)
    }else{
       let obj={
            id:outline.value[index].sections[iidx].id,
            name:outline.value[index].sections[iidx].name,
            parent_id:outline.value[index].sections[iidx].parent_id,
            bk_id:outline.value[index].sections[iidx].bk_id
         }
        console.log("更新小节");
       upDareOutLine(obj)
    }

  } else {
    if (!(await verifyAdd())) {
      return;
    }
    tmpChangeContent.value = outline.value[index].sections[iidx].name;
  }
  outline.value[index].sections[iidx].edit =
    !outline.value[index].sections[iidx].edit;

  //小结修改时光标定位  gyzheng 20220621
  let pos = "lessonRef" + index + "" + iidx;
  proxy.$refs[pos][0].focus();

  addOutLineData.value.name = outline.value[index].sections[iidx].name;
  // 小节父级的id等于章节的id
  addOutLineData.value.parent_id =outline.value[index].id
  
  console.log(addOutLineData.value);


};


// 删除章节的方法

const delRowChapter=(id)=>{
  delOutline(id).then(res=>{
    if(!res){
      ElMessage.success("删除成功")
      getSyllList()
    }else{
      ElMessage.error(res.response.data)
    } 
  })

}

//删除章
const delChapter = async (item,id) => {
  // 判断下面有无小节
  if(item.sections.length){
    ElMessage.error("该章节下存在小节,不能删除")
    return
  
  };
  
  delRowChapter(id)
};

//删除节
const delLesson = async (id) => {
  delRowChapter(id)
  
};

let lessonRules = reactive({
  name: [{ required: true, message: "小节名称必须填写", trigger: "blur" }],
});

//验证必填项
let valueEmpty = (value, msg) => {
  return new Promise((resolve) => {
    if (!value) {
      ElMessage({
        message: msg + "不能为空",
        type: "error",
      });
      resolve(false);
    } else if (value.length < 2 || value.length > 30) {
      ElMessage({
        message: msg + "字数限制在2-30",
        type: "error",
      });

      resolve(false);
    } else {
      resolve(true);
    }
  }).catch((err) => {
    // console.log(err);
  });
};

//验证是否可以新建
let verifyAdd = () => {
  let arr = [];
  outline.value.forEach((item) => {
    let sections = item.sections || [];
    arr.push(...sections);
  });

  let son = arr.every((item) => {
    return !item.edit;
  });

  let every = outline.value.every((item) => {
    return !item.edit;
  });

  return new Promise((resolve, reject) => {
    if (!(son && every)) {
      ElMessage({
        // message: "存在正在编辑的章节，不允许新增",
        message: "存在正在编辑的章节，请先完善正在编辑的章节",
        type: "error",
      });
      resolve(false);
    } else {
      reject(true);
    }
  }).catch(() => {
    return true;
  });
};

//导入按钮
const clickImport = () => {
  ElMessage.warning("开发中，未开放...");
};

getSyllList();
// getMaterialList();

// 点击教学设计按钮
const goDesignDialog = (e) => { 
  sDialog.value.openDialog(e);

};




</script>

<style lang="scss" scoped>
.icon {
  cursor: pointer;

  span {
    vertical-align: middle;
  }

  .iconfont {
    font-size: 22px;
    vertical-align: middle;
  }

  &:hover {
    color: #333;
  }
}

.syllabus {
  .content {
    padding: 0 50px 0 50px;

    .main {
      .public {
        color: #333;
        padding: 0 20px 0 30px;
      }

      .bigChapter {
        background: #fbfbfb !important;
      }

      .chapter {
        height: 60px;
        width: 100%;
        border: 1px #ddd dashed;
        font-size: 18px;
        line-height: 60px;
        margin-bottom: 20px;
      }

      .lesson {
        line-height: 46px;
        background: #f7f7f7;
        border: 1px dashed #ddd;
        margin-left: 90px;
        padding-left: 30px;
        margin-bottom: 20px;
        font-size: 16px;

        .text {
          cursor: pointer;
        }
      }

      .add {
        color: #2988fe;
        background: #f7f7f7;
        cursor: pointer;

        &:hover {
          background: #eee;
        }
      }

      .finish {
        background: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-style: solid;

        .title {
          display: flex;
          align-items: center;

          .num {
            padding-right: 20px;
          }

          .ipt {
            width: 490px;
          }
        }

        .acts {
          font-size: 14px;
          color: #666;
          display: flex;

          div {
            padding: 5px 10px;
            cursor: pointer;
          }

          .del:hover {
            color: #ff5733;
          }

          .edit:hover {
            color: #2988fe;
          }
        }
      }

      .compile {
        background: #fff;
        border-style: solid;
        padding: 30px 30px;

        .row {
          width: 750px;

          .tabs {
            display: flex;
            padding-top: 10px;

            .box {
              padding: 0px 10px;
              background: #f6f6f6;
              border-radius: 5px;
              margin-right: 10px;
              font-size: 14px;
              color: #666;
              cursor: pointer;
            }
          }

          .info {
            font-size: 16px;
            color: #2988fe;

            span {
              color: #f56c6c;
              cursor: pointer;
              padding: 0 10px;
            }
          }

          .button {
            width: 100px;
            height: 30px;
            font-size: 14px;
            color: #fff;
            background: #2988fe;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 20px;
            cursor: pointer;

            &.default {
              background: #fff;
              border: 1px solid #999;
              color: #999;
            }
          }

          .bigBtn {
            width: 150px;
            height: 40px;
            font-size: 18px;
            margin-top: 20px;
            margin-right: 20px;
          }
        }
      }
    }

    .btnGroup {
      position: fixed;
      left: calc(50% - 100px);
      bottom: -80px;
      transition: 0.3s;

      .view {
        display: flex;
        justify-content: center;

        .btn .el-button {
          width: 200px;
          height: 50px;
          border-radius: 50px;
          font-size: 18px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 0 20px;
        }
      }
    }

    .btnGroup.active {
      bottom: 80px;
    }
  }
}

.designDialogHead {
  p {
    font-size: 18px;
  }
}
</style>

<style>
.el-pager li.is-active {
  border: 1px solid #409eff;
  border-radius: 5px;
}

.el-radio.el-radio--large .el-radio__label {
  width: 100%;
}
</style>
